package com.example.check.cooperative.service.impl;

import com.example.check.cooperative.mapper.CooperativeItemCheckMapper;
import com.example.check.cooperative.mapper.CooperativeItemMapper;
import com.example.check.cooperative.pojo.CooperativeItem;
import com.example.check.cooperative.pojo.CooperativeItemCheck;
import com.example.check.cooperative.service.CooperativeItemService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.time.LocalDateTime;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

@Service
public class CooperativeItemServiceImpl implements CooperativeItemService {

    @Autowired
    private CooperativeItemMapper itemMapper;
    
    @Autowired
    private CooperativeItemCheckMapper checkMapper;

    @Override
    public List<CooperativeItem> listByTrip(Integer tripId, Integer userId) {
        List<CooperativeItem> items = itemMapper.selectByTripId(tripId);
        
        // 如果有userId，查询该用户的查验状态并合并到结果中
        if (userId != null) {
            try {
                List<CooperativeItemCheck> checks = checkMapper.selectByTripIdAndUserId(tripId, userId);
                Map<Integer, Boolean> checkMap = checks.stream()
                    .collect(Collectors.toMap(CooperativeItemCheck::getItemId, CooperativeItemCheck::getChecked));
                
                // 为每个物品设置当前用户的查验状态
                for (CooperativeItem item : items) {
                    Boolean userChecked = checkMap.get(item.getId());
                    item.setChecked(userChecked != null ? userChecked : false);
                }
            } catch (Exception e) {
                // 如果查询查验记录失败（可能是表不存在），使用物品本身的checked状态
                // 这样可以在表创建之前也能正常工作
                System.err.println("查询用户查验状态失败，使用默认状态: " + e.getMessage());
                // 保持items的原始checked状态
            }
        }
        
        return items;
    }

    @Override
    public boolean addItem(CooperativeItem item) {
        item.setCreatedAt(LocalDateTime.now());
        item.setUpdatedAt(LocalDateTime.now());
        if (item.getChecked() == null) {
            item.setChecked(false);
        }
        return itemMapper.insert(item) > 0;
    }

    @Override
    @Transactional
    public boolean updateChecked(Integer itemId, Boolean checked, Integer userId, String scope) {
        try {
            if ("all".equals(scope)) {
                // 如果是"给所有人都添加"，需要获取该物品的所有相关用户
                // 这里简化处理：获取该物品所在行程的所有成员
                // 实际应该查询 cooperative_trip_members 表
                // 暂时只更新当前用户
                CooperativeItemCheck check = new CooperativeItemCheck();
                check.setItemId(itemId);
                check.setUserId(userId);
                check.setChecked(checked != null ? checked : false);
                return checkMapper.insertOrUpdate(check) > 0;
            } else {
                // "仅给我自己添加"，只更新当前用户的查验状态
                CooperativeItemCheck check = new CooperativeItemCheck();
                check.setItemId(itemId);
                check.setUserId(userId);
                check.setChecked(checked != null ? checked : false);
                return checkMapper.insertOrUpdate(check) > 0;
            }
        } catch (Exception e) {
            // 如果表不存在，降级到更新物品本身的checked状态
            System.err.println("更新用户查验状态失败，降级到更新物品状态: " + e.getMessage());
            return itemMapper.updateCheckedStatus(itemId, checked != null ? checked : Boolean.FALSE) > 0;
        }
    }

    @Override
    public boolean deleteItem(Integer itemId) {
        // 删除物品时，同时删除相关的查验记录
        checkMapper.deleteByItemId(itemId);
        return itemMapper.deleteById(itemId) > 0;
    }

    @Override
    public boolean resetChecked(Integer tripId, Integer userId) {
        if (userId != null) {
            try {
                // 重置指定用户的查验状态
                return checkMapper.deleteByTripIdAndUserId(tripId, userId) > 0;
            } catch (Exception e) {
                // 如果表不存在，降级到重置物品状态
                System.err.println("重置用户查验状态失败，降级到重置物品状态: " + e.getMessage());
                return itemMapper.resetCheckedByTripId(tripId) > 0;
            }
        } else {
            // 重置所有用户的查验状态（保留旧的逻辑作为兼容）
            return itemMapper.resetCheckedByTripId(tripId) > 0;
        }
    }

    @Override
    public boolean deleteByTripId(Integer tripId) {
        // 删除行程时，相关的查验记录会通过外键级联删除
        return itemMapper.deleteByTripId(tripId) > 0;
    }
}


